/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState } from 'react';
import ProTable from '@ant-design/pro-table';
import KbDetailModal from './details/index';
import OrderForm from './OrderForm';
import ProCard from '@ant-design/pro-card';
import { DrawerForm } from '@ant-design/pro-form';
import { message } from 'antd';
import { columns } from './index.config';
import type { TableListItem } from '@/pages/tools/orderManage/index.d';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import type { ProFormInstance } from '@ant-design/pro-form';
import { useSelector } from 'umi';
import { getOrderList } from '@/services/tools/orderManage';
import styles from './index.less';

const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [formData, setFormData] = useState<{}>();
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [status, setStatus] = useState(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [currentId, setCurrentId] = useState<string>('');

  const tableReload = (cb?: () => void) => {
    const { reset } = actionRef.current || {};
    actionRef.current?.reload(false);
    if (reset) {
      reset();
    }
    if (typeof cb === 'function') {
      cb();
    }
  };
  const onReset = () => {
    setStatus(true);
    setFormData({});
    tableReload();
  };
  const handleFormSubmit = async (values: any) => {
    setFormData(values);
    tableReload();
  };
  const getOrderManageList = async (params: any, form: any) => {
    const { current: page, pageSize } = params;
    const { orderNo, waybill, user, courier } = form;
    if (status) {
      setStatus(false);
      return {};
    } else if (orderNo || waybill || user || courier) {
      delete params.current;
      return getOrderList({ page, pageSize, ...params, ...form }).then((res) => {
        const {
          code,
          data: { result: data, total },
          msg,
        } = res;
        if (code === 0) {
          return {
            data,
            total,
          };
        } else {
          message.error(msg);
          return {};
        }
      });
    } else {
      message.error('请填写订单号、运单号、发件人或业务员');
      return {};
    }
  };
  const handleDetail = (params: TableListItem) => {
    new Promise<void>((resolve) => {
      setCurrentId(params.id);
      return resolve();
    }).then(() => setVisible(true));
  };
  const drawerCallBack = () => {
    setVisible(false);
    tableReload();
  };
  const optionsColumns: ProColumns<TableListItem>[] = [
    {
      title: '操作',
      search: false,
      align: 'center',
      dataIndex: 'options',
      fixed: 'right',
      width: winSize === 'xs' ? 80 : 120,
      render: (_, record) => {
        const optionType = record.status == '0';
        return (
          <a
            style={{ color: optionType ? 'red' : 'blue' }}
            onClick={handleDetail.bind(this, record)}
          >
            {optionType ? '立即处理' : '订单详情'}
          </a>
        );
      },
    },
  ];

  return (
    <>
      <ProCard style={{ width: '100%', marginBottom: 16 }}>
        <OrderForm onSubmit={handleFormSubmit} onReset={onReset} />
      </ProCard>
      <ProTable<TableListItem>
        actionRef={actionRef}
        rowKey='id'
        className={styles.orderManage}
        request={(values) => getOrderManageList(values, formData)}
        manualRequest
        columns={[...columns, ...optionsColumns]}
        options={false}
        scroll={{ x: 1200 }}
        pagination={{
          pageSize: 20,
          showQuickJumper: false,
          showSizeChanger: false,
        }}
        search={false}
      />
      <DrawerForm
        title='订单详情'
        visible={visible}
        formRef={formRef}
        onVisibleChange={setVisible}
        drawerProps={{
          destroyOnClose: true,
          footerStyle: { display: 'none' },
        }}
        width={winSize === 'xs' ? 350 : 1200}
      >
        <KbDetailModal orderId={currentId} visible={visible} drawerCallBack={drawerCallBack} />
      </DrawerForm>
    </>
  );
};

export default Index;
